#pragma once

#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include"Logger.hpp"
#include<netinet/in.h>
#include<arpa/inet.h>
#include<strings.h>
#include<functional>
#include"InetAddr.hpp"

using callback_t = std::function<void \
                  (int socket_fd, std::string message, InetAddr addr)>;

class UdpServer
{   
public:
    UdpServer(uint16_t port, callback_t cb)
        :_socket_fd(-1)
        ,_port(port)
        ,_is_running(false)
        ,_cb(cb)
    { }

    void Init()
    {
        _socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_socket_fd < 0)
        {
            LOG(LogLevel::FATAL) << "create socket error";
            exit(1);
        }
        LOG(LogLevel::INFO) << "create socket success:" << _socket_fd;
        InetAddr local(_port);
        int ret = bind(_socket_fd, local.Addr(), local.Len());
        if(ret < 0)
        {
            LOG(LogLevel::FATAL) << "bind socket error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind socket success";
    }

    void Start()
    {
        _is_running = true;
        while(_is_running)
        {
            char buffer[1024];
            buffer[0] = 0;
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t ret = recvfrom(_socket_fd, buffer, sizeof(buffer), 0, 
                                  (struct sockaddr*)&peer, &len);
            if(ret > 0)
            {
                buffer[ret] = 0;
                InetAddr client(peer);
                LOG(LogLevel::DEBUG) << "get a client info# " << client.Ip()
                                     << "-" << client.Port() << ":" << buffer;
                std::string message = buffer;
                _cb(_socket_fd, message, client);
            }
        }
        _is_running = false;
    }

    void Stop()
    {
        _is_running = false;
    }

private:
    //std::string _ip;
    int _socket_fd;
    uint16_t _port;
    bool _is_running;
    callback_t _cb;
};